package main

import (
	"errors"
	"gitee.com/lanfengye2002/base/common"
	"io"
	"math/rand"
	"os"
	"strings"
	"time"
)

func main() {
	log.Info("<小米同城会专用抽奖系统服务已启动>")
	log.Info("沈阳小米同城会祝君中奖")
	log.Info("全部参与抽奖名单：%s", strings.Join(usersAllList, ","))
	log.Info("已抽奖名单：%s", strings.Join(alreadyList, ","))
	log.Info("参加抽奖名单：%s", strings.Join(userlist,","))
	log.Info("!!!!!!!!!警告：抽奖过程中请不要关闭该程序，否则无法继续抽奖！!!!!!!!")
	openApi()
}

//随机多个中奖名单 调用多次rand_one抽奖  t-false从未中奖人员中抽取 true-从全部参与者中抽取
func randMulti(num int, t bool) ([]string, error) {
	var result []string
	var err error

	if t && num > len(usersAllList) {
		return nil, errors.New("抽奖人数必须小于参与人数")
	}
	if !t && num > len(userlist) {
		return nil, errors.New("抽奖人数必须小于参与人数")
	}

	result, err = randMultis(num, t)
	if err != nil {
		return nil, err
	}
	if !t{
		writeAlready(result)
		remove(result)
	}

	return result, nil
}

//随机抽取多个数据
func randMultis(num int, t bool) ([]string, error) {
	var u []string
	var list = make([]string, 0, num)
	if t {
		u=make([]string,len(usersAllList))
		copy(u,usersAllList)
	} else {
		u=make([]string,len(userlist))
		copy(u,userlist)
	}

	u = shuffle(u)
	log.Info("洗牌后名单顺序：%s", strings.Join(u, ","))

	for i := 0; i < num; i++ {
		l := len(u)
		n := rand.New(rand.NewSource(time.Now().UnixNano())).Intn(l)
		list = append(list, u[n])
		u = append(u[:n], u[n+1:]...)
	}
	return list, nil
}

//写入中奖记录
func writeAlready(name []string) {
	var f *os.File
	var err error

	if f, err = os.OpenFile(common.Path+"mi/already.ini", os.O_APPEND|os.O_CREATE, 0666); err != nil {
		check(err)
		return
	}
	defer f.Close()

	for _, v := range name {
		_, err = io.WriteString(f, "\r\n") //写入换行
		check(err)
		_, err = io.WriteString(f, v) //写入文件(字符串)
		check(err)
	}
	mutexAlreadylist.Lock()
	defer mutexAlreadylist.Unlock()
	alreadyList = append(alreadyList, name...)
	alreadyList=RemoveRepByLoop(alreadyList)
}



//删除已抽奖人员 在抽奖名单中
func remove(name []string) {
	mutexUserlist.Lock()
	defer mutexUserlist.Unlock()

	var listMap=slice2Map(name)
	var temp=make([]string,0,len(userlist))

	for _,v:=range userlist{
		if _,ok:=listMap[v];!ok{
			temp=append(temp,v)
		}
	}
	userlist=temp
}

//处理名单数据  去掉已抽奖人员
func handleMingdan() {
	userlist = make([]string, 0, len(usersAllList))
	var alreadyMap = slice2Map(alreadyList)

	for _, v := range usersAllList {
		if _, ok := alreadyMap[v]; !ok {
			userlist = append(userlist, v)
		}
	}
}
